import socket
import ipaddress

_local_ip = ""


def get_local_ip(peer_ip: str, mask: str) -> str:
    """
    找出本机和某个ip peer_ip（子网掩码为mask）在同一个网段上的ip。
    如果找不到，返回空字符串
    """
    global _local_ip
    if _local_ip != "":
        return _local_ip
    # 获取本机所有IP地址
    addrs = socket.getaddrinfo(socket.gethostname(), None)

    # 定义目标IP和子网掩码
    IP_X = peer_ip  # 示例IP，请替换为实际的IP地址
    MASK = mask  # 示例子网掩码，请替换为实际的子网掩码

    # 将目标IP和子网掩码转换为网络地址
    target_ip = ipaddress.ip_address(IP_X)
    subnet_mask = ipaddress.ip_network(f"0.0.0.0/{MASK}", strict=False).netmask

    # 找出属于目标网段的IP地址
    same_subnet_ips = []
    for item in addrs:
        # 每个item是一个元组，其中第五个元素是(ip, port)元组，ip是本机的IP地址
        ip = item[4][0]
        # 忽略非IPv4地址
        if ":" in ip:
            continue
        # 将本机IP地址转换为网络地址并与目标网络地址比较
        host_ip = ipaddress.ip_address(ip)
        host_network = int(host_ip) & int(subnet_mask)
        target_network = int(target_ip) & int(subnet_mask)
        print(host_network, target_network)
        if host_network == target_network:
            same_subnet_ips.append(ip)

    # 打印属于目标网段的IP地址
    for ip in same_subnet_ips:
        _local_ip = ip
        return ip
    return ""
